package com.cndw.kungfu.model.pvp.war;

import java.util.concurrent.ScheduledFuture;

import com.cndw.kungfu.config.ConstantsConfig;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.CrossProxySerialize;
import com.cndw.kungfu.model.pvp.api.ApiCore;

/**
 * 全服天下第一启动函数
 * 
 * @author fantadust [9677889@qq.com]
 * @date 2012-8-8 下午6:44:31
 */
public class WarWorldPross implements Runnable {
	private static ScheduledFuture<?> task;

	private static int lastTime;

	@Override
	public void run() {
		try {

			WarWorldData warWorldData = WarCoreCenter.getWarWorld();
			warWorldData.checkCycle();
			if (CrossProxySerialize.getInstance().getCrossStep() < 3 && ConstantsConfig.isLocalHost()) {
				return;
			}
			warWorldData.runBoss();
			if (warWorldData.getStep() >= 3 && task != null) {
				task.cancel(false);
				LogUtil.getMain().debug("war world task stop.....");
			}
			if (lastTime + 7200 <= TimeProcesser.getUnixTime()) {
				lastTime = TimeProcesser.getUnixTime();
				WarEvent.runUpdateWorldScore();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public synchronized static void runBoss() {

		if (!ApiCore.isCrossServer()) {
			return;
		}
		WarWorldData warWorldData = WarCoreCenter.getWarWorld();
		warWorldData.checkCycle();
		if (warWorldData.getStep() >= 3) {
			if (task != null) {
				task.cancel(false);
			}
			return;
		}
		int currentTime = TimeProcesser.getUnixTime();
		int diff = WarConfig.getWorldBegin() + WarConfig.eliminateBegin - currentTime;
		WarWorldPross warWorldPross = new WarWorldPross();

		task = Context.getTimerServer().scheduleAtFixedRate(warWorldPross, diff, 10);
		LogUtil.getMain().debug("war world  begin " + diff);

	}

}
